package cn.rocky.zuosheng;

public class CodeHeadSort {

    public static void headSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        // O(N)
        for (int i = 0; i < arr.length; i++) {
            headInsert(arr, i); // O(logN)
        }
        int headSize = arr.length;
        swap(arr, 0, --headSize);
        while (headSize > 0) {
            heapify(arr, 0, headSize);
            swap(arr, 0, --headSize);
        }
    }

    //  某个数据在处在index位置,往上继续移动
    public static void headInsert(int[] arr, int index) {
        while (arr[index] > arr[index - 1]) {
            swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void heapify(int[] arr, int index, int headSize) {
        int left = index * 2 + 1;
        while (left < headSize) {
            int largest = left + 1 < headSize &&
                    arr[left + 1] > arr[left]
                    ? left + 1
                    : left;

            largest = arr[largest] > arr[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(arr, largest, index);
            index = largest;
            left = index * 2 + 1;
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
